package com.gztms.usermgnt.filter;

import com.gztms.usermgnt.pojo.LoginUser;
import com.gztms.utils.JwtUtil;
import com.gztms.utils.RedisCache;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Zoey
 * @date 2023/3/8 21:18
 * @Description jwt认证过滤器
 **/
@Component
//@RequiredArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 1、获取token
        String token = httpServletRequest.getHeader("token");

        // 若token为空，则直接放行，因为不会设置SecurityContextHolder，
        // 后面就没法认证通过，会被后面的filter拦截
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        // 2、解析token
        String uid;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            uid = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }

        // 3、从redis中获取用户信息
        String redisKey = "login:"+ uid;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)) {
            throw new RuntimeException("用户未登录或登录超时，请重新登录");
        }

        // 4、存入SecurityContextHolder
        // TODO 暂未获取权限信息
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities()
                );
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 5、放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);

    }
}
